Ext.define('SenchaApp.controller.MainCtrl', {
    extend: 'Ext.app.Controller',
    refs: [
        {
            ref: 'carGrid',
            selector: 'grid[action=carsGridView]'
        },
        {
            ref: 'mainContainer',
            selector: 'bordercenter[action=mainContainer]'
        },
        {
            ref: 'detailsContainer',
            selector: 'form[action=carDetails]'
        }

    ],
    init: function () {
        this.control(
            {
                'treepanel[action=viewCars]': {
                    itemclick: this.reloadCarGrid
                },
                'grid[action=carsGridView]': {
                    itemclick: this.gridClick
                },
                'cardetailscontainer button[action=saveidbutton]': {
                    click: this.updateCarRecord
                }
            }
        );

    },

    reloadCarGrid: function (view, rec, item, index, eventObj) {
        var carGrid = this.getCarGrid();
        var mainContainer = this.getMainContainer();
        var rootUrl = '/api/Sencha/GetAllCars';
        if (rec.raw.url) {
            var url = rootUrl + rec.raw.url;
            carGrid.store.proxy.api.read = url;
            carGrid.store.load();
            mainContainer.setTitle(rec.raw.heirarchy);
        }
    },

    gridClick: function(view, rec, item, index, eventObj) {
        var detailsCarView = this.getDetailsContainer();
        detailsCarView.loadRecord(rec);
    },
    
    updateCarRecord: function (view, e, eOpts) {
        //get all references
        var detailsCarView = this.getDetailsContainer();
        var carGrid = this.getCarGrid();

        //update the stores locally
        var newVal = detailsCarView.getValues();
        var currentRec = detailsCarView.getRecord();
        if (currentRec) {
            currentRec.set(newVal);
            //make it sync to the database by updating the modified store
            carGrid.store.sync();
        }

    }
});
